﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;

namespace FastShip88
{
    public partial class TransferReq : System.Web.UI.Page
    {
        DBAccess.UsersDataContext db;
        decimal totalAmount;

        public string StartChoice
        {
            get { return ViewState["StartChoice"].ToString(); }
            set { ViewState["StartChoice"] = value; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            db = new DBAccess.UsersDataContext();

            lblError.Visible = false;
            lblSuccess.Visible = false;


        }

      


        protected void int_create_req_grid()
        {
           
            int userId = Utility.GetUserId(this);

            var parcels = from p in db.ParcelInfos
                          where p.UserId == userId && (p.StatusId == 10 || p.StatusId == 65 /*分拆取消*/ ||
                                    p.StatusId == 75 /*合并取消*/ || p.StatusId == 78 /*新包裹合并完成*/  || p.StatusId == 95 /*中转请求取消*/ )
                          select new { p.Id, p.UserId, p.ParcelNo, p.ShopId, p.Description, p.Weight, p.ArriveDate, StatusName = p.ParcelStatus.name };

            gvAvailParcels.DataSourceID = null;
            gvAvailParcels.DataSource = parcels;
            gvAvailParcels.DataBind();

            var q_addrs = from q in db.UserAddresses
                          where q.UserId == userId
                          select q;

            int selectedIndex = -1;
            int i=0;
            string strReceiptor = "";
            foreach (var addr in q_addrs)
            {
                string address = addr.Address;
                address = address.Replace("@", "");
                addr.Address = address;

                if (addr.IsDefault.HasValue && addr.IsDefault.Value)
                {
                    selectedIndex = i;
                    strReceiptor = addr.receiptor;
                }
                       
                i++;
            }

            ddlAddrs.DataSource = q_addrs;
            ddlAddrs.DataBind();

            if (selectedIndex != -1)
            {
                ddlAddrs.SelectedIndex = selectedIndex;
                lblReceiptor.Text = strReceiptor;
            }

        }


      

        protected void gvResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvAvailParcels.PageIndex = e.NewPageIndex;
            int_create_req_grid();
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            StartChoice = rdoChoice.SelectedValue;

            switch (rdoChoice.SelectedValue)
            {
                case "create":
                    multiView.ActiveViewIndex = 1;
                    int_create_req_grid();
                    break;
                case "viewPending":
                    multiView.ActiveViewIndex = 2;
                    init_pending_req_grid(false);
                    break;
                case "viewHistory":
                    multiView.ActiveViewIndex = 2;
                    init_pending_req_grid(true);
                    break;
            }

        }

        private void init_pending_req_grid(bool isViewPaid)
        {
            int userId = Utility.GetUserId(this);

            var transReqs = from t in db.TransferReqs
                            from b in db.UserBills
                            from addr in db.UserAddresses
                            where t.UserId == userId && t.IsCancelled == false && t.IsUserConfirmed == false &&
                                    t.UserBillId == b.Id && b.IsCleared == isViewPaid && t.TransferAddr == addr.id
                            select new {t.Id, t.Description, t.ReqDate, t.IsCancelled, t.Memo , addr.receiptor, TransferAddr = addr.Address } ;


            gvPendingReq.DataSourceID = null;
            gvPendingReq.DataSource = transReqs;
            gvPendingReq.DataBind();

            lblUnpaidTransReq.Visible = !isViewPaid;
            lblPaidTransReq.Visible = isViewPaid;

            divParcelsInReq.Visible = false;
        }

        protected void btnCreateReq_Click(object sender, EventArgs e)
        {
            int userId = Utility.GetUserId(this);
            int addrId = SafeConvert.ToInt(ddlAddrs.SelectedValue);
            decimal unitPrice7 = Utility.GetUnitPriceByFeeType(7, userId);
            int totalBillId  = 0;

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var transReq = new DBAccess.TransferReq();
                    transReq.UserId = userId;
                    transReq.ReqDate = DateTime.Now;
                    transReq.IsCancelled = false;
                    transReq.IsUserConfirmed = false;
                    transReq.TransferAddr = addrId;
                    transReq.Description = txtDescription.Text.Trim();

                    db.TransferReqs.InsertOnSubmit(transReq);
                    db.SubmitChanges();

                    int transReqId = transReq.Id;

                    var q_total_bill = new DBAccess.UserBill();
                    q_total_bill.UserId = userId;
                    q_total_bill.FeeTypeId = 12; //汇总扣款
                    q_total_bill.Date = DateTime.Now;
                    q_total_bill.IsCancelled = false;
                    q_total_bill.IsCleared = false;
                    q_total_bill.TransReqId = transReqId;
                    db.UserBills.InsertOnSubmit(q_total_bill);
                    db.SubmitChanges();

                    totalBillId = q_total_bill.Id;
                    transReq.UserBillId = totalBillId;
                    db.SubmitChanges();

                    totalAmount = 0;

                    foreach (GridViewRow gvr in gvAvailParcels.Rows)
                    {
                        CheckBox cb = (CheckBox)gvr.FindControl("chkSelect"); // .Cells[0].Controls[0];
                        if (cb.Checked)
                        {
                            int pid = SafeConvert.ToInt(gvAvailParcels.DataKeys[gvr.RowIndex].Value.ToString());

                            var parcel = (from p in db.ParcelInfos
                                          where p.Id == pid
                                          select p).First();

                            parcel.StatusId = 80; //请求中转
                            parcel.TransferReqId = transReqId;

                            db.SubmitChanges();

                            DBAccess.UserBill q_bill;

                            if (parcel.ParcelNo != null && parcel.ParcelNo.ToString().Length > 0)  //入站包裹直接邮寄要付签收服务的费用
                            {
                                //decimal unitPrice1 = Utility.GetUnitPriceByFeeType(1, userId);

                                //q_bill = new DBAccess.UserBill();
                                //q_bill.UserId = userId;
                                //q_bill.FeeTypeId = 1; //签收服务
                                //q_bill.Date = DateTime.Now;
                                //q_bill.IsCancelled = false;
                                //q_bill.IsCleared = true;
                                //q_bill.Quantity = (int)(parcel.Weight + 0.7); //超过0.3算一磅。
                                //q_bill.Amount = (decimal)q_bill.Quantity.Value * unitPrice1;
                                //q_bill.ParcelId = pid;
                                //q_bill.ClearFrom = totalBillId;
                                //q_bill.TransReqId = transReqId;

                                //db.UserBills.InsertOnSubmit(q_bill);
                                //db.SubmitChanges();

                                //totalAmount += q_bill.Amount.Value;
                            }
                            else //存在“分拆”和“合并”服务费
                            {
                                var q_duebills = from q in db.UserBills
                                                 where q.UserId == userId && q.IsCancelled == false && q.IsCleared == false && q.ParcelId == pid &&
                                                    ( q.FeeTypeId == 4  || q.FeeTypeId == 5)
                                                    //q.FeeTypeId != 12 /*汇总扣款*/ && q.FeeTypeId != 9 /*充值*/ && q.FeeTypeId != 10 /*退款*/ && q.FeeTypeId != 14 /*支付宝收款*/
                                                 select q;

                                foreach (var q in q_duebills)
                                {
                                    q.ClearFrom = totalBillId;
                                    q.IsCleared = true;
                                    db.SubmitChanges();

                                    if (q.Amount.HasValue)
                                        totalAmount += q.Amount.Value;
                                }


                            }


                            if (parcel.Premium.HasValue && parcel.Premium.Value > 0)
                            {
                                q_bill = new DBAccess.UserBill();
                                q_bill.UserId = userId;
                                q_bill.FeeTypeId = 11; //海关报税
                                q_bill.Date = DateTime.Now;
                                q_bill.IsCancelled = false;
                                q_bill.IsCleared = true;
                                q_bill.Amount = parcel.Premium.Value;
                                q_bill.ParcelId = pid;
                                q_bill.ClearFrom = totalBillId;
                                q_bill.TransReqId = transReqId;

                                db.UserBills.InsertOnSubmit(q_bill);
                                db.SubmitChanges();

                                totalAmount += q_bill.Amount.Value;

                            }


                            q_bill = new DBAccess.UserBill();
                            q_bill.UserId = userId;
                            q_bill.FeeTypeId = 7; //中转服务
                            q_bill.Date = DateTime.Now;
                            q_bill.IsCancelled = false;
                            q_bill.IsCleared = true;
                            q_bill.Quantity = (int)(parcel.Weight + 0.7);
                            q_bill.Amount = (decimal)q_bill.Quantity.Value * unitPrice7;
                            q_bill.ParcelId = pid;
                            q_bill.ClearFrom = totalBillId;
                            q_bill.TransReqId = transReqId;

                            db.UserBills.InsertOnSubmit(q_bill);
                            db.SubmitChanges();

                            totalAmount += q_bill.Amount.Value;

                        }
                    }

                    //q_total_bill = (from q in db.UserBills where q.Id == totalBillId select q).First();
                    totalAmount = decimal.Round(totalAmount, 2);
                    q_total_bill.Amount = totalAmount;
                    db.SubmitChanges();

                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    lblError.Visible = true;

                    return;
                }

                ts.Complete();

            }

            if (!lblError.Visible)
            {
                multiView.ActiveViewIndex = 4;
                lblCreateReqSuccess.Visible = true;
                lblTotalAmount.Text = totalAmount.ToString();
                lblUserBillId.Text = totalBillId.ToString();
            }
        }

 
        protected void imgAliPay_Click(object sender, ImageClickEventArgs e)
        {
            AlipayConfig con = new AlipayConfig();
            string partner = con.Partner;
            string key = con.Key;
            string seller_email = con.Seller_email;
            string input_charset = con.Input_charset;
            string notify_url = con.Notify_url;
            string return_url = con.Return_url;
            string show_url = con.Show_url;
            string sign_type = con.Sign_type;

            ////////////////////////////////////////////////////////////////////////////////////////////////////

            ///////////////////////以下参数是需要通过下单时的订单数据传入进来获得////////////////////////////////
            //必填参数
            string out_trade_no = lblUserBillId.Text;  //请与贵网站订单系统中的唯一订单号匹配
            string subject = "88快递中转";                      //订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
            string body = "帐单ID为：" +  lblUserBillId.Text   ; //订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
            string total_fee = lblTotalAmount.Text;                    //订单总金额，显示在支付宝收银台里的“应付总额”里

            //扩展功能参数——默认支付方式
            string paymethod = "directPay";                       //默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)，初始值
            string defaultbank = "";                                        //默认网银代号，代号列表见http://club.alipay.com/read.php?tid=8681379 初始值

            //扩展功能参数——防钓鱼
            //请慎重选择是否开启防钓鱼功能
            //exter_invoke_ip、anti_phishing_key一旦被设置过，那么它们就会成为必填参数
            //建议使用POST方式请求数据
            string anti_phishing_key = "";                                  //防钓鱼时间戳
            string exter_invoke_ip = "";                                    //获取客户端的IP地址，建议：编写获取客户端IP地址的程序
            //如：
            //exter_invoke_ip = "";
            //anti_phishing_key = AlipayFunction.Query_timestamp(partner);  //获取防钓鱼时间戳函数


            //扩展功能参数——其他
            string extra_common_param = "";                                 //自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
            string buyer_email = "";			                            //默认买家支付宝账号

            //扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)
            string royalty_type = "";                                   //提成类型，该值为固定值：10，不需要修改
            string royalty_parameters = "";
            //提成信息集，与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
            //各分润金额的总和须小于等于total_fee
            //提成信息集格式为：收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
            //如：
            //royalty_type = "10";
            //royalty_parameters = "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二";

            /////////////////////////////////////////////////////////////////////////////////////////////////////

            //构造请求函数，无需修改
            AlipayService aliService = new AlipayService(partner, seller_email, return_url, notify_url, show_url, out_trade_no, subject, body, total_fee, paymethod, defaultbank, anti_phishing_key, exter_invoke_ip, extra_common_param, buyer_email, royalty_type, royalty_parameters, key, input_charset, sign_type);
            string sHtmlText = aliService.Build_Form();

            lbButton.Text = sHtmlText;
        }

        protected void btnPay4Pending_Click(object sender, EventArgs e)
        {
            if (gvPendingReq.SelectedIndex == -1)
            {
                lblError.Text = "请选中一条中转记录";
                lblError.Visible = true;
                return;
            }

            int transReqId = SafeConvert.ToInt( gvPendingReq.SelectedDataKey.Value );

            var q_trans = (from t in db.TransferReqs
                          from b in db.UserBills
                          where t.Id == transReqId && t.UserBillId == b.Id
                          select b).First();

            multiView.ActiveViewIndex = 4;

            lblTotalAmount.Text = q_trans.Amount.Value.ToString();
            lblUserBillId.Text = q_trans.Id.ToString();

        }

        protected void btnCancelTransReq_Click(object sender, EventArgs e)
        {

            int userId = Utility.GetUserId(this);
            int transReqId = SafeConvert.ToInt(gvPendingReq.SelectedDataKey.Value);


            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    int totalBillId = 0;

                    var transReq = (from q in db.TransferReqs
                                    where q.Id == transReqId
                                    select q).First();

                    totalBillId = transReq.UserBillId.Value;

                    var q_innerTotalBills = from q in db.UserBills
                                            where q.ClearFrom == totalBillId && q.FeeTypeId == 12 /*汇总扣款*/
                                            select q;

                    if (q_innerTotalBills.Count() > 0)
                    {
                        lblError.Text = "该中转请求已经付款过或有追加付款情况，不能撤销。";
                        lblError.Visible = true;
                        ts.Dispose();
                        return;
                    }

                    transReq.IsCancelled = true;
                    db.SubmitChanges();

                    var q_total_bill = (from q in db.UserBills
                                            where q.Id == totalBillId
                                            select q).First();
                    q_total_bill.IsCancelled = true;
                    db.SubmitChanges();


                    var q_duebills = from q in db.UserBills
                                     where q.ClearFrom == totalBillId && q.TransReqId != transReqId && q.IsCancelled == false && q.IsCleared == true &&
                                        q.FeeTypeId != 12 /*汇总扣款*/ && q.FeeTypeId != 9 /*充值*/ && q.FeeTypeId != 10 /*退款*/ && q.FeeTypeId != 14 /*支付宝收款*/
                                     select q;

                    foreach (var q in q_duebills)
                    {
                        q.ClearFrom = null;
                        q.IsCleared = false;
                        q.Memo = q.Memo + "BillCancel " + totalBillId.ToString() + ".";
                        db.SubmitChanges();
                    }

                     var q_otherBills = from q in db.UserBills
                                     where q.ClearFrom == totalBillId && q.TransReqId == transReqId && q.IsCancelled == false && q.IsCleared == true &&
                                        q.FeeTypeId != 12 /*汇总扣款*/ && q.FeeTypeId != 9 /*充值*/ && q.FeeTypeId != 10 /*退款*/ && q.FeeTypeId != 14 /*支付宝收款*/
                                     select q;

                     foreach (var q in q_otherBills)
                     {
                         q.IsCancelled = true;
                         db.SubmitChanges();

                         if (q.ParcelId.HasValue)
                         {
                             int pid = q.ParcelId.Value;

                             var parcel = (from p in db.ParcelInfos
                                           where p.Id == pid
                                           select p).First();

                             parcel.StatusId = 95; //请求中转取消
                             parcel.TransferReqId = null;
                             db.SubmitChanges();

                         }
                     }
                    
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    lblError.Visible = true;

                    return;
                }

                ts.Complete();

            }

            if (!lblError.Visible)
            {
                init_pending_req_grid(false);
                lblSuccess.Text = "已成功取消中转请求。";
                lblSuccess.Visible = true;
            }


        }

        protected void ddlAddrs_SelectedIndexChanged(object sender, EventArgs e)
        {
            int addrId = SafeConvert.ToInt( ddlAddrs.SelectedValue );

            var q_addr = (from q in db.UserAddresses
                          where q.id == addrId
                          select q).First();

            lblReceiptor.Text = q_addr.receiptor;
        }

        protected void gvPendingReq_SelectedIndexChanged(object sender, EventArgs e)
        {
            divParcelsInReq.Visible = true;
            gvParcelsInReq.DataBind();
        }

    }
}
